package com.xy.server.server;

import java.io.Serializable;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xy.server.service.FaceService;
import com.xy.server.service.MosaicService;
import com.xy.server.util.ImageMergeUtil;
import com.xy.server.util.ServerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;


@Component
public class MessageEventHandler
{
    private final SocketIOServer server;

    @Autowired
    MosaicService mosaicService;

    @Autowired
    FaceService faceService;

//    @Autowired
//    private ClientInfoRepository clientInfoRepository;

    @Autowired
    public MessageEventHandler(SocketIOServer server)
    {
        this.server = server;
    }
    //添加connect事件，当客户端发起连接时调用，本文中将clientid与sessionid存入数据库
    //方便后面发送消息时查找到对应的目标client,
    @OnConnect
    public void onConnect(SocketIOClient client)
    {
        System.out.println("on connect client");
    }

    //添加@OnDisconnect事件，客户端断开连接时调用，刷新客户端信息
    @OnDisconnect
    public void onDisconnect(SocketIOClient client)
    {
        System.out.println("on disconnect client");
    }


    private static boolean mosiacFinish = false;
    private static boolean playFinish = false;

    private static boolean webCamUsing = false;
    private static int webCamFaceCount = 0;

    private final int VIDEO_HELLO = 0;
    private final int VIDEO_NEUTRAL = 1;
    private final int VIDEO_HAPPINESS = 2;
    private final int VIDEO_ANGER = 3;
    private final int VIDEO_FEAR = 4;
    private final int VIDEO_SURPRISE = 5;
    private final int VIDEO_SADNESS = 6;
    private final int VIDEO_IDLE = 7;
    private final int VIDEO_TWO_PERSON = 8;

    private void goToNextRound(){
        System.out.println("---- next round ----");
        //System.out.println("mosiacFinish " + mosiacFinish);
        System.out.println("playFinish " + playFinish);

        //if(mosiacFinish && playFinish){
        if(playFinish){
            server.getBroadcastOperations().sendEvent("next-round", new Object());
        }
    }
    @OnEvent(value = "tv")
    public void onEventTV(SocketIOClient client, AckRequest request, Object data) throws Exception
    {
        System.out.println("---- tv here ----");

        server.getBroadcastOperations().sendEvent("tv", "tv player");
    }

    private boolean isLock(){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH);//获取月份
        int day=cal.get(Calendar.DATE);//获取日
        int hour=cal.get(Calendar.HOUR_OF_DAY);//小时

        int minute=cal.get(Calendar.MINUTE);//分
        int second=cal.get(Calendar.SECOND);//秒
        int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK);//一周的第几天
        System.out.println("now "+year+"year"+month+"month"+day+"day      "+hour+"hour"+minute+"minute"+second+"second      week "+WeekOfYear);

        if(hour >= 9  && hour < 18){
            return false;
        }
        System.out.println("service is lock");
        return true;
    }

    @OnEvent(value = "people")
    public synchronized void onEventPeople(SocketIOClient client, AckRequest request, Object obj) throws Exception
    {
        System.out.println("---- people ----");


        if(isLock()){
            server.getBroadcastOperations().sendEvent("lock", new Object());
            return ;
        }

        Map<String,Object> data = (HashMap <String,Object>)obj;
        // broadcast messages to all clients
        Map map = faceService.capture();

        server.getBroadcastOperations().sendEvent("people", map);

    }
    //消息接收入口，当接收到消息后，查找发送目标客户端，并且向该客户端发送消息，且给自己发送消息
    @OnEvent(value = "face")
    public synchronized void onEventFace(SocketIOClient client, AckRequest request, Object obj) throws Exception
    {
        System.out.println("---- face ----");


        if(isLock()){
            server.getBroadcastOperations().sendEvent("lock", new Object());
            return ;
        }

        server.getBroadcastOperations().sendEvent("start", new Object());

        Map<String,Object> data = (HashMap <String,Object>)obj;

        mosiacFinish = false;
        playFinish = false;

        // broadcast messages to all clients
        Map map = faceService.capture();

        server.getBroadcastOperations().sendEvent("face", map);

        if(map != null){
            Map<String,Object> result = (Map<String,Object>)map.get("result");

            Map<String,Object> mapMosaic = mosaicService.mosaic(result);

            server.getBroadcastOperations().sendEvent("mosaic", mapMosaic);

            mosiacFinish = true;
            System.out.println("mosaic finish");
//            goToNextRound();
        }
    }

    @OnEvent(value = "mosaic-template")
    public void onEventMosaicTemplate(SocketIOClient client, AckRequest request, MessageInfo data) throws Exception
    {
        System.out.println("---- mosaic-template ----");

        mosaicService.mosaicTemplate();
        server.getBroadcastOperations().sendEvent("mosaic-template", new Object());

    }

    @OnEvent(value = "play-video")
    public void onEventPlayVideo(SocketIOClient client, AckRequest request, Object obj) throws Exception
    {
        System.out.println("---- play-video ----");

        Map<String,Object> data = (HashMap <String,Object>)obj;
        System.out.println("finish video index " + data.get("index"));
        int index = Integer.valueOf( data.get("index").toString());

        server.getBroadcastOperations().sendEvent("play-video", obj);
    }

    @OnEvent(value = "play-finish")
    public void onEventPlayFinish(SocketIOClient client, AckRequest request, Object obj) throws Exception
    {
        System.out.println("---- play-finish ----");

//        Map<String,Object> data = (HashMap <String,Object>)obj;
//        System.out.println("finish video index " + data.get("video_index"));
//        int video_index = Integer.valueOf( data.get("video_index").toString());
        playFinish = true;
        goToNextRound();
        //server.getBroadcastOperations().sendEvent("play-finish", new Object());

    }
}
